package com.xtxk.service.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xtxk.entity.User;
import com.xtxk.mapper.UserMapper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    public void query() {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        List<User> users = userMapper.selectList(userQueryWrapper);
        System.out.println("最后集合的大小：" + users.size());
    }

    @Override
    public void insert(User user) {
        long start = System.currentTimeMillis();
//        int insert = userMapper.insert(user);
//        System.out.println(insert);

        // 测试批量插入
        List<User> list = new ArrayList<>(1000);
        for (int i = 0; i < 1000; i++) {
            User user1 = new User();
            user1.setName("batch" + i);
            user1.setPassword("the i value is " + i);
            list.add(user1);
        }

        // 批量插入
        batchInsert(list);

        System.out.println("插入1k数据 总耗时："+(System.currentTimeMillis()-start));
    }

    @Override
    public void update(User user) {
//        userMapper.updateById(user);
        User wrapperUser = new User();
        wrapperUser.setId(1445801264688246786L);
        user.setName("lambda update wrapper");
        LambdaUpdateWrapper<User> userLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        userLambdaUpdateWrapper.setEntity(wrapperUser);
        userMapper.update(user, userLambdaUpdateWrapper);
    }

    @Override
    public void delete(User user) {
        LambdaUpdateWrapper<User> objectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        objectLambdaUpdateWrapper.setEntity(user);
        userMapper.delete(objectLambdaUpdateWrapper);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        List<User> users = userMapper.selectList(queryWrapper);
        System.out.println(Arrays.toString(users.toArray()));
    }


    private void batchInsert(List<User> list) {
        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        if (!CollectionUtils.isEmpty(list)) {
            try {
                int size = list.size();
                System.out.println("begin to insert the list size" + size);
                for (int i = 0, n = list.size(); i < n; i++) {
                    User user = list.get(i);
                    mapper.insert(user);// 插入

                    // 手动保证1000个提交一次
                    if ((i > 0 && i % 1000 == 0) || i == size - 1) {
                        sqlSession.commit();
                        sqlSession.clearCache();
                    }
                }
            } catch (Exception e) {
                sqlSession.rollback();// 报错回滚
            } finally {
                sqlSession.close();
            }
        }
    }

    @Override
    public void page() {
        IPage<User> userIPage = new Page<>(1,100,false);
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper();

        IPage iPage = userMapper.selectMapsPage(userIPage, queryWrapper);
        long total = iPage.getTotal();
        long pages = iPage.getPages();

        System.out.println("总页数："+pages);
        System.out.println("总记录数："+total);
    }
}
